package ru.spb.nicetu.altx.mnemo.math.managers;

import java.util.HashMap;
import java.util.Map;

import ru.spb.nicetu.altx.mnemo.extpoint.model.typeConverter.IConverter;

public class ValueTypeConverterManager {

  private Map<Class<?>, Map<Class, IConverter>> type2TypeConverterMap = new HashMap<Class<?>, Map<Class, IConverter>>();

  private static ValueTypeConverterManager instance = new ValueTypeConverterManager();

  public static ValueTypeConverterManager getInstance() {
    return instance;
  }

  public void addType2TypeConverter(Class<?> fromClass, Class<?> toClass,
      IConverter converter) {
    Map<Class, IConverter> toTypeConverterMap = type2TypeConverterMap
        .get(fromClass);

    if (toTypeConverterMap == null){
      toTypeConverterMap = new HashMap<Class, IConverter>();
      type2TypeConverterMap.put(fromClass, toTypeConverterMap);
    }

    IConverter existConverter = toTypeConverterMap.get(toClass);
    if (existConverter != null) {
      System.out.println("Внимание: конвертер " + fromClass.getName() + " <-> "
          + toClass.getName() + " уже существует ("
          + existConverter.getClass().getName() + "). Перезаписан не будет");
      return;
    }
    
    toTypeConverterMap.put(toClass, converter);
  }
  
  /**
   * @param fromClass
   * @param toClass
   * @return конвертер [ fromClass -> toClass ] или null
   */
  public IConverter getConverter(Class<?> fromClass, Class<?> toClass){

    Map<Class, IConverter> toTypeConverterMap = type2TypeConverterMap.get(fromClass);
    if (toTypeConverterMap == null)
      return null;
    
    IConverter converter = toTypeConverterMap.get(toClass);
    return converter;    
  }

  /**
   * 
   * @param fromClass
   * @param toClass
   * @return true, если fromClass может быть преведен к toClass, иначе false
   */
  public Boolean canCastTo(Class<?> fromClass, Class<?> toClass){
    try{
      return type2TypeConverterMap.get(fromClass).get(toClass) != null;
    } catch (Exception e) {
      return false;
    }
//    return false;
  }
}
